/**
 * 设计二、三中的shell
*/
#include "commutils.h"

//当前工作目录
vector<folderiNode> workpath;
//用户输入的指令及参数
vector<string> cmdv;
//用户id，默认-1表示空
int userid = -1;
//是否第一次循环
bool firsttime = true;

/**
 * 主函数，程序入口
*/
int main(int argc, char *argv[])
{
    string cmdstr, line;
    showTitle();
    userid = login();
    //将工作目录置为root
    workpath.push_back(readFolderInode(0));
    //共享内存
    void *shm = NULL;
    int shmid;
    struct shared_mem_st *shared = NULL;
    //创建共享内存
    shmid = shmget((key_t)MEMKEY, sizeof(struct shared_mem_st), 0666|IPC_CREAT);
    if(shmid == -1)
    {
        fprintf(stderr, "shmget failed\n");
        exit(EXIT_FAILURE);
    }
    //将共享内存连接到当前进程的地址空间
    shm = shmat(shmid, (void*)0, 0);
    if(shm == (void*)-1)
    {
        fprintf(stderr, "shmat failed\n");
        exit(EXIT_FAILURE);
    }
    printf("Memory attached at 0x%X\n", (long int)shm);
    //共享内存映射到变量
    shared = (struct shared_mem_st*)shm;
    while (1)
    {
        printPath(workpath);
        if (firsttime)
        {
            getline(cin, line);
            firsttime = false;
        }
        getline(cin, line);
        if (line.empty())
        {
            cout << usage_input;
            continue;
        }
        cmdv.clear();
        SplitString(line, cmdv, " ");
        cmdstr = cmdv[0];
        if (!cmdstr.compare("fcy"))
        {
            cout << "FCY is a nice guy.\n";
            continue;
        }
        else if (!cmdstr.compare("exit"))
        {
            cout << "bye.\n";
            break;
        }
        else if (!cmdstr.compare("shutdown"))
        {
            //write
            shared->userid=userid;
            strcpy(shared->cmd,"shutdown");
            break;
        }
        //写入共享内存
        while(shared->userid!=-1){
            cout<<shared->userid<<" waiting send...\n";
            sleep(1);
        }
        //===write===
        shared->userid=userid;
        strcpy(shared->workpath,getStringPath(workpath).c_str());
        strcpy(shared->cmd,line.c_str());
        //===========
        while(shared->userid != userid + REPLYSIGN){
            cout<<shared->userid<<" waiting reply...\n";
            sleep(1);
        }
        getFolderByPath(workpath, shared->workpath);
        cout<<"[reply]\n";
        cout<<shared->output<<endl;
        //清空输出
        char* buf=new char[MEMOUT_SZ]{};
        strcpy(shared->output,buf);
        //结束占用
        shared->userid=-1;
    }
    //把共享内存从当前进程中分离
    if(shmdt((void*)shared) == -1)
    {
        fprintf(stderr, "shmdt failed\n");
        exit(EXIT_FAILURE);
    }
    exit(0);
}